/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.redkale.util;

import java.util.List;
import java.util.concurrent.*;

/**
 * 简单的CompletableFuture与Flow.Subscriber的结合类。
 *
 * <p>
 * 详情见: https://redkale.org
 *
 * @since 2.5.0
 * @param <T> T
 */
public class SubscriberFuture<T> extends CompletableFuture<T> implements Flow.Subscriber<T> {

    protected T rs;

    public static final <T> CompletableFuture<List<T>> createFluxFuture(Flow.Publisher<T> publisher) {
        SubscriberListFuture<T> future = new SubscriberListFuture<>();
        publisher.subscribe(future);
        return future;
    }

    public static final <T> CompletableFuture<T> createMonoFuture(Flow.Publisher<T> publisher) {
        SubscriberFuture<T> future = new SubscriberFuture<>();
        publisher.subscribe(future);
        return future;
    }

    @Override
    public void onSubscribe(Flow.Subscription s) {
        s.request(Integer.MAX_VALUE);
    }

    @Override
    public void onNext(T item) {
        rs = item;
    }

    @Override
    public void onError(Throwable t) {
        completeExceptionally(t);
    }

    @Override
    public void onComplete() {
        complete(rs);
    }
}
